$(document).ready(function () {
    /*新增角色权限表单验证*/
    $("#addRoleForm,#updateRoleDialog").bootstrapValidator({
        message: 'This value is not valid',
        excluded: [':disabled'], //[':disabled', ':hidden', ':not(:visible)'] //设置隐藏组件可验证
        feedbackIcons: {
            validating: 'glyphicon glyphicon-refresh'
        },
        fields: {
            rolename: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请输入角色名称'
                    },
                    regexp: {
                        regexp: /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
                        message: '用户名为大小写字母、中文、数字、下划线的组合'
                    }
                }
            },
            flag: {
                trigger: "change", //针对赋值的文本框执行change事件
                validators: {
                    notEmpty: {
                        message: '请选择类型'
                    }
                }
            }
        }
    });
    loadRoleDetail();
    var btnElement = '#SearchForm .dis,#roleManagementToobar .dis';
    btnJurisdiction(btnElement);//查询当前用户的按钮权限
})

/*加载表格数据*/
function loadRoleDetail(){
    $('#roleManageTable').bootstrapTable('destroy');/*表格加载前先销毁原有数据*/
    var name = $("#SearchForm input[name='name']").val();
    /* 初始化表格数据 */
    $('#roleManageTable').bootstrapTable({
        method: 'POST',
        url:"../role/queryRole",   /* 调用后台接口加载数据 */
        queryParamsType:'',
        queryParams:function (params) {
            var pageSize = params.pageSize;
            var pageNum = params.pageNumber;
            return {  /*参数*/
                pageSize:pageSize,
                pageNum:pageNum,
                name:name
            };
        },
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",
        cache: false,     // 不缓存
        striped: true,    // 隔行加亮
        pagination: true, //是否显示分页
        toolbar: '#roleManagementToobar',//工具列
        singleSelect:true, //单选
        pageSize: 10,
        pageNumber: 1,     //初始化加载第一页，默认第一页
        pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
        sidePagination: "server",
        showColumns: true,
        showRefresh: true,  //是否显示刷新按钮
        clickToSelect: true,  //是否启用点击选中行
        columns: [
            {field: "select",title: "选择",checkbox: true,width: 20},
            {field: '',title: '序号',width: 20,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
            {field:"name",title:"角色名称",align:"center",valign:"middle",sortable:"true"},
            {field:"createDate",title:"创建时间",align:"center",valign:"middle",sortable:"true",formatter:function (value, row, index) {return dateFormat(new Date(value), "yyyy-MM-dd");}},
            {field:"createPerson",title:"创建人",align:"center",valign:"middle",sortable:"true"},
            {field:"remark",title:"备注",align:"center",valign:"middle",sortable:"true"},
            {field:"cz",title:"操作",align:"center",valign:"middle",width:100,formatter: optionsFormatter}
        ],
        formatLoadingMessage: function () {
            return "请稍等，正在加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        /*onClickRow:function(row,ele){  //表格单击选中事件
            var index = ele[0].dataset.index;
            row.select = true;
            var option = $('#roleManageTable').bootstrapTable("getOptions");
            var rows = option.data;
            for (var i=0;i<rows.length;i++){
                if (i==index){
                    rows[index].select = true;
                }else{
                    rows[i].select = false;
                }
                $('#roleManageTable').bootstrapTable("updateRow",{
                    index:i,
                    row:rows[i]
                });
            }
        },*/
        responseHandler: function(res) {
            var total ,rows;
            if (res!=null&&res.length!=0) {
                total = res.total;
                rows = res.rows;
            }else {
                total = 0;
                rows = new Array();
            }

            return {
                "total":total,//total,//总页数
                "rows":rows  //数据
            };
        },
        onPostBody:function(){
            var btnElement = '.chkUserList';
            btnJurisdiction(btnElement);//查询当前用户的按钮权限
        }
    });

    $(window).resize(function (e, value, row, index) {
        $('#roleManageTable').bootstrapTable('resetView');
    });
}

/*刷新表格*/
function refreshDetailTab() {
    $('#roleManageTable').bootstrapTable('refresh');
}

/*主界面条件查询*/
function searchdata(){
    loadRoleDetail();
}

/*角色名称查询回车事件*/
document.onkeydown = function(event){
    if (event.keyCode == 13) {
        event.cancelBubble = true;
        event.returnValue = false;
        loadRoleDetail();/*调用加载表格数据的方法*/
    }
}

/*新增角色权限弹出框*/
function AddRole(){
    $("#addRoleDialog").modal("show");
}

/*新增弹出框内重置按钮点击事件*/
function resetAddRole(){
    $("#addRoleForm").find(":input").not(":button").val("");
    $("#flag").val("");
    $('#addRoleForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
    var treeObj = $.fn.zTree.getZTreeObj("treeDemo"); //清空树结构选中项
    treeObj.checkAllNodes(false);
}

/*修改弹出框内重置按钮点击事件*/
function resetUpdateRole() {
    $("#updateRoleForm").find(":input").not(":button,#updateRolename,#updateflag").val("");
    var treeObj = $.fn.zTree.getZTreeObj("edittree"); //清空树结构选中项
    treeObj.checkAllNodes(false);
}

/*查看角色下用户按钮*/
function optionsFormatter(value, row, index){
    var html = '<button type="button" class="dis chkUserList btn btn-info" value="查看用户" title="查看用户" onclick="checkUser(\''+row.id+'\')" ><i class="fa fa-user-o"></i></button>&nbsp;&nbsp;&nbsp;&nbsp;';
    return html;
};

/*查看角色下用户按钮点击事件*/
function checkUser(roleid){
    $("#checkUserBox").modal("show");
    $('#userInfoTable').bootstrapTable('destroy');/*表格加载前先销毁原有数据*/
    /* 初始化表格数据 */
    $('#userInfoTable').bootstrapTable({
        method: 'POST',
        url:"../role/qru",   /* 调用后台接口加载数据 */
        queryParamsType:'',
        queryParams:function (params) {
            var pageSize = params.pageSize;
            var pageNum = params.pageNumber;
            return {  /*参数*/
                pageSize:pageSize,
                pageNum:pageNum,
                roleid:roleid
            };
        },
        contentType:"application/x-www-form-urlencoded; charset=UTF-8",
        cache: false,                // 不缓存
        striped: true,              // 隔行加亮
        pagination: true,          //是否显示分页
        singleSelect:true,        //单选
        pageSize: 10,
        pageNumber: 1,           //初始化加载第一页，默认第一页
        pageList: [5, 10, 20, 30, 50], //可供选择的每页的行数（*）
        sidePagination: "server",
        showColumns: true,
        showRefresh: true,     //是否显示刷新按钮
        clickToSelect: true,  //是否启用点击选中行
        columns: [
            /*{field: "select",title: "选择",checkbox: true,width: 20},*/
            {field: '',title: '序号',width: 20,align:"center",valign:"middle",formatter: function (value, row, index) {return index+1;}},
            {field:"name",title:"用户名称",align:"center",valign:"middle",sortable:"true"},
            {field:"email",title:"邮箱",align:"center",valign:"middle",sortable:"true"},
            {field:"phone",title:"电话",align:"center",valign:"middle",sortable:"true"},
            {field:"organizationId",title:"组织机构",align:"center",valign:"middle",sortable:"true"}
        ],
        formatLoadingMessage: function () {
            return "请稍等，正在加载中...";
        },
        formatNoMatches: function () {
            return '无符合条件的记录';
        },
        responseHandler: function(res) {
            var total ,rows;
            if (res!=null&&res.length!=0) {
                total = res.total;
                rows = res.rows;
            }else {
                total = 0;
                rows = new Array();
            }

            return {
                "total":total,//total,//总页数
                "rows":rows  //数据
            };
        }
    });

    $(window).resize(function (e, value, row, index) {
        $('#userInfoTable').bootstrapTable('resetView');
    });
}


/*新增角色及权限时加载权限树结构*/
var setting = {
    view : {
        dblClickExpand : false,
        selectedMulti : false
    },
    check: {
        enable: true
    },
    data: {
        key:{
            checked:"checked",
            children:"children",
            name:"menuName",
            title:"",
            url:""
        },
        simpleData: {
            enable:true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: ""
        }
    },
    async : {
        enable : true,
        url : "../role/dyQuery",
        dataFilter: filter
    },
    callback:{
        onCheck:onCheck
    }
};

function filter(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    for (var i=0, l=childNodes.length; i<l; i++) {
        childNodes[i].menuName = childNodes[i].menuName.replace(/\.n/g, '.');
    }
    return childNodes;
}

$(document).ready(function(){
    $.fn.zTree.init($("#treeDemo"), setting);
});

/*树结构权限复选框点击事件，获取节点funcid*/
function onCheck(e,treeId,treeNode){
    var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
        nodes=treeObj.getCheckedNodes(true),
        v="";
    for(var i=0;i<nodes.length;i++){
        v+=nodes[i].id+",";  //获取选中节点的值
    }
    return v;
}

/*新增角色权限提交按钮点击事件*/
function submitaddRole(){
    var rolename = $("#addRoleForm input[name='rolename']").val();
    var flag = $("#flag").val();
    var remark = $("#addRoleForm input[name='remark']").val();
    /*获取所有复选框选中项的值放入一个字符串中*/
    var treeObj=$.fn.zTree.getZTreeObj("treeDemo"),
        nodes=treeObj.getCheckedNodes(true),
        menuid="",//菜单id
        methid = ""; //按钮id
    for(var i=0;i<nodes.length;i++){
        if(nodes[i].cof==1){  /*1-菜单*/
            menuid += nodes[i].id+",";  //获取选中节点的值
        }else{  /*2-按钮*/
            methid += nodes[i].id+",";  //获取选中节点的值
        }
    }
    //去掉最后一个逗号
    if (menuid.length > 0) {
        menuid = menuid.substr(0, menuid.length - 1);
    }

    if (methid.length > 0) {
        methid = methid.substr(0, methid.length - 1);
    }

    var $formlist = $('#addRoleForm');
    var data = $formlist.data('bootstrapValidator');
    if (data) {
        // 修复记忆的组件不验证
        data.validate();
        if (!data.isValid()) {
            return false;
        }
    }

    $.ajax({
        url:"../role/insert",
        data:{"rolename":rolename,"menuid":menuid,"methid":methid,"flag":flag,"remark":remark},
        type:"post",
        dataType:"json",
        success:function(data){
            if (data.code==1){ //成功
                layer.alert(data.mess, {icon: 1});
                $("#addRoleDialog").modal("hide");
                $("#addRoleForm").find(":input").not(":button").val("");
                var treeObj = $.fn.zTree.getZTreeObj("treeDemo"); //清空树结构选中项
                treeObj.checkAllNodes(false);
                $('#addRoleForm').bootstrapValidator('resetForm');//重置表单是重置表单验证
                $("#flag").val("");
                refreshDetailTab();
            }else{
                layer.alert(data.mess, {icon: 2});
            }
        }
    })

}

/*修改角色下用户权限树结构*/
var settings = {
    view : {
        dblClickExpand : false,
        selectedMulti : false
    },
    check: {
        enable: true,
        chkboxType:  { "Y": "p", "N": "s" }
    },
    data: {
        key:{
            checked:"checked",
            children:"children",
            name:"menuName",
            title:"",
            url:""
        },
        simpleData: {
            enable:true,
            idKey: "id",
            pIdKey: "parentId",
            rootPId: ""
        }
    },
    async : {
        enable : true,
        dataFilter: filters
    }
};
function filters(treeId, parentNode, childNodes) {
    if (!childNodes) return null;
    for (var i=0, l=childNodes.length; i<l; i++) {
        childNodes[i].menuName = childNodes[i].menuName.replace(/\.n/g, '.');
    }
    return childNodes;
}

/*修改按钮点击事件*/
function UpdateRole(){
    var thRow = $('#roleManageTable').bootstrapTable('getSelections');
    if (thRow.length < 1) {
        layer.alert('请选择一个角色进行修改！', {icon: 2});
    } else {
        if(thRow[0].name==="超级管理员"){
            layer.msg("超级管理员权限无权修改!",{time:2000});
        }else{
            /*if(thRow[0].flag==1){ //内置角色不允许修改
                layer.msg("内置角色不允许修改!",{time:2000});
            }else{*/
                $("#updateRoleDialog").modal("show");
                $("#updateRolename").attr("readonly","readonly");
                $("#updateflag").attr("disabled","disabled");
                $("#updateRoleForm input[name='rolename']").val(thRow[0].name);
                $("#updateRoleForm input[name='remark']").val(thRow[0].remark);
                $("#updateflag").find("option[value='"+thRow[0].flag+"']").attr("selected",true);

                /*查询全部树并勾选改用户已有的权限*/
                var treeNode = "";
                $.ajax({
                    type: "POST",
                    url:"../role/dyQuery",
                    async: false,
                    dataType:"json",
                    success:function(data){
                        treeNode = data;
                    }
                })

                /*查询当前用户权限树*/
                $.ajax({
                    type: "POST",
                    url:"../role/uprole",
                    data:{"roleid":thRow[0].id},
                    dataType:"json",
                    success:function(data){
                        $.fn.zTree.init($("#edittree"), settings, treeNode);
                        if (data.length > 0) {
                            var treeObj = $.fn.zTree.getZTreeObj("edittree");
                            for (var i = 0; i < data.length; i++) {
                                var nodes = treeObj.getNodesByParam("id", data[i].id, null);
                                treeObj.checkNode(nodes[0],true,true);
                                treeObj.expandNode(nodes[0], true); //展开选中的
                            }
                        }
                    }
                })
            //}
        }
    }
}


/*修改弹出框提交按钮点击事件*/
function submitupdateRole(){
    $("#updateflag").removeAttr("disabled");
    var thRow = $('#roleManageTable').bootstrapTable('getSelections');
    var rolename = $("#updateRoleForm input[name='rolename']").val();
    var flag = $("#updateflag").val();
    var remark = $("#updateRoleForm input[name='remark']").val();
    /*获取所有复选框选中项的值放入一个字符串中*/
    var treeObj=$.fn.zTree.getZTreeObj("edittree"),
        nodes=treeObj.getCheckedNodes(true),
        menuid="",//菜单id
        methid = ""; //按钮id
    for(var i=0;i<nodes.length;i++){
        if(nodes[i].cof==1){  /*1-菜单*/
            menuid += nodes[i].id+",";  //获取选中节点的值
        }else{  /*2-按钮*/
            methid += nodes[i].id+",";  //获取选中节点的值
        }
    }
    //去掉最后一个逗号
    if (menuid.length > 0) {
        menuid = menuid.substr(0, menuid.length - 1);
    }

    if (methid.length > 0) {
        methid = methid.substr(0, methid.length - 1);
    }

    var $formlist = $('#updateRoleForm');
    var data = $formlist.data('bootstrapValidator');
    if (data) {
        // 修复记忆的组件不验证
        data.validate();
        if (!data.isValid()) {
            return false;
        }
    }

    $.ajax({
        url:"../role/update",
        data:{"rolename":rolename,"id":thRow[0].id,"menuid":menuid,"methid":methid,"flag":flag,"remark":remark},
        type:"post",
        dataType:"json",
        success:function(data){
            if (data.code==1){ //成功
                layer.alert(data.mess, {icon: 1});
                $("#updateRoleDialog").modal("hide");
                /*$("#updateRoleForm").find(":input").not(":button").val("");*/
                var treeObj = $.fn.zTree.getZTreeObj("treeDemo"); //清空树结构选中项
                treeObj.checkAllNodes(false);
                $('#updateRoleDialog').bootstrapValidator('resetForm');//重置表单是重置表单验证
                $("#updateflag").val("");
                refreshDetailTab();
            }else{
                layer.alert(data.mess, {icon: 2});
            }
        }
    })
}

/*删除角色及权限按钮点击事件*/
function DeleteRole(){
    var rows = $("#roleManageTable").bootstrapTable('getSelections');
    if(rows.length<1){
        layer.alert("请选择要删除的角色！", {icon: 2});
    }else{
        /*if(rows[0].flag==1){  //内置角色
            layer.msg("系统内置角色无权删除！");
        }else{*/
            layer.confirm('确定要删除所选数据？', {icon: 3, title:'提示'}, function(){
                $.ajax({
                    type: "POST",
                    url: '../role/delete',
                    dataType:"json",
                    data:{"name":rows[0].name,"id":rows[0].id,"flag":rows[0].flag},
                    success:function(data){
                        if(data.code==1){
                            layer.msg(data.mess, {icon: 1});
                            refreshDetailTab();
                        }else{
                            layer.msg(data.mess, {icon: 2});
                        }
                    }
                })
            })
        //}
    }
}

/*时间戳格式化*/
var dateFormat=function (now,mask) {
    var d = now;
    var zeroize = function (value, length)
    {
        if (!length) length = 2;
        value = String(value);
        for (var i = 0, zeros = ''; i < (length - value.length); i++)
        {
            zeros += '0';
        }
        return zeros + value;
    };

    return mask.replace(/"[^"]*"|'[^']*'|\b(?:d{1,4}|m{1,4}|yy(?:yy)?|([hHMstT])\1?|[lLZ])\b/g, function ($0)
    {
        switch ($0)
        {
            case 'd': return d.getDate();
            case 'dd': return zeroize(d.getDate());
            case 'ddd': return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
            case 'dddd': return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
            case 'M': return d.getMonth() + 1;
            case 'MM': return zeroize(d.getMonth() + 1);
            case 'MMM': return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
            case 'MMMM': return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
            case 'yy': return String(d.getFullYear()).substr(2);
            case 'yyyy': return d.getFullYear();
            case 'h': return d.getHours() % 12 || 12;
            case 'hh': return zeroize(d.getHours() % 12 || 12);
            case 'H': return d.getHours();
            case 'HH': return zeroize(d.getHours());
            case 'm': return d.getMinutes();
            case 'mm': return zeroize(d.getMinutes());
            case 's': return d.getSeconds();
            case 'ss': return zeroize(d.getSeconds());
            case 'l': return zeroize(d.getMilliseconds(), 3);
            case 'L': var m = d.getMilliseconds();
                if (m > 99) m = Math.round(m / 10);
                return zeroize(m);
            case 'tt': return d.getHours() < 12 ? 'am' : 'pm';
            case 'TT': return d.getHours() < 12 ? 'AM' : 'PM';
            case 'Z': return d.toUTCString().match(/[A-Z]+$/);
            // Return quoted strings with the surrounding quotes removed
            default: return $0.substr(1, $0.length - 2);
        }
    });
}